//
//  ktool.swift
//  Riji
//
//  Created by  on 2022/8/21.
//

import UIKit

class ktool: NSObject {

    //MARK: - 清除缓存
    /// 清除缓存
    @objc class func clearCache()
    {
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! as String
        if  FileManager.default.fileExists(atPath: cachePath)
        {
            let array = FileManager.default.subpaths(atPath: cachePath)!
            for fileName in array
            {
                let absolutePath = cachePath+fileName
                do {
                    try FileManager.default.removeItem(atPath:absolutePath)
                } catch  {}
            }
        }
    }

    //MARK: -获取缓存大小
    ///获取缓存大小
    @objc class func cacheSize()->CGFloat
    {
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! as String
        let fileMana = FileManager.default
        if fileMana.fileExists(atPath: cachePath){return 0}
        
        let files = fileMana.subpaths(atPath: cachePath)!
        var dataSize = 0
        for fileName in files {
            let path = cachePath + "\(fileName)"
            do
            {
                let floder = try fileMana.attributesOfItem(atPath: path)
                for (key, fileSize) in floder
                {
                    // 累加
                    if key == FileAttributeKey.size {
                        dataSize += (fileSize as AnyObject).integerValue
                    }
                }
            }
            catch
            {
                print("获取缓存出错了")
            }
        }
        return CGFloat(dataSize) / 1024.0 / 1024.0
    }

    
}
